<template>
  <div class="box">
    <el-table :data="tableData" style="width: 100%; height: 400px" :row-class-name="tableRowClassName">
      <el-table-column prop="ais" label="是否报文">
        <template #default="scope">
          <div>{{ scope.row.ais === 1 ? "是" : "否" }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="aisContent" label="报文内容" width="200">
      </el-table-column>
      <el-table-column prop="vhf" label="是否VHF喊话">
        <template #default="scope">
          <div>{{ scope.row.vhf === 1 ? "是" : "否" }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="vhfContent" label="VHF喊话内容" width="200">
      </el-table-column>
      <el-table-column prop="warning" label="是否预警">
        <template #default="scope">
          <div>{{ scope.row.warning === 1 ? "是" : "否" }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="startDate" label="开始日期" width="180">
        <template #default="scope">
          <div>{{ formatDate(scope.row.startDate) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="endDate" label="结束日期" width="180">
        <template #default="scope">
          <div>{{ formatDate(scope.row.endDate) }}</div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button link size="small" @click="editRule(scope.row)">修改</el-button>
          <el-button link size="small" @click="delRule(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="btn">
      <el-button type="primary" @click="addRule">添加规则</el-button>
    </div>

    <el-dialog :title="ruleTitle + '规则'" top="30%" v-model="isNew" width="30%" @close="handleClose"
      :modal="false">
      <div class="newBox">
        <el-form :model="form" ref="ruleForm" label-width="100px">
          <div class="newBox_list">
            <div class="newBox_list_title">是否预警：</div>
            <el-select v-model="form.warning" placeholder="请选择" class="elInpMn">
              <el-option key="1" label="是" :value="1"> </el-option>
              <el-option key="0" label="否" :value="0"> </el-option>
            </el-select>

            <div class="newBox_list_title">区域地点：</div>
            <el-input :value="ruleTitle" :readonly="true" class="elInpTwo"></el-input>
          </div>

          <div class="newBox_list">
            <div class="newBox_list_title">AIS报文：</div>
            <el-select v-model="form.ais" placeholder="请选择" class="elInpMn">
              <el-option key="1" label="是" :value="1"> </el-option>
              <el-option key="0" label="否" :value="0"> </el-option>
            </el-select>
            <el-input v-model="form.aisContent" :disabled="!form.ais" placeholder="请输入报文内容" class="elInp"></el-input>
          </div>

          <div class="newBox_list">
            <div class="newBox_list_title">VHF喊话：</div>
            <el-select v-model="form.vhf" placeholder="请选择" class="elInpMn">
              <el-option key="1" label="是" :value="1"> </el-option>
              <el-option key="0" label="否" :value="0"> </el-option>
            </el-select>
            <el-input v-model="form.vhfContent" :disabled="!form.vhf" placeholder="请输入VHF喊话内容" class="elInp"></el-input>
          </div>
          <div class="newBox_list">
            <div class="newBox_list_title">日期：</div>
            <div class="custom-date-wrapper">
              <el-date-picker 
                v-model="datetimerone" 
                type="datetimerange" 
                range-separator="至" 
                start-placeholder="开始日期"
                end-placeholder="结束日期" 
                class="elInpthree" 
                @change="changedatetimerone" 
                value-format="YYYY-MM-DD HH:mm:ss"
                :shortcuts="dateShortcuts"
                :default-time="defaultTime"
                popper-class="elDatePicker">
              </el-date-picker>
              <div v-if="form.startDate && form.endDate" class="date-display">
                {{ formatDate(form.startDate) }} 至 {{ formatDate(form.endDate) }}
              </div>
            </div>
          </div>
          <div class="newBox_list">
            <div class="newBox_list_title">每天定时：</div>
            <div class="custom-date-wrapper">
              <el-time-picker 
                is-range 
                v-model="datetimertwo" 
                range-separator="至" 
                start-placeholder="开始时间"
                end-placeholder="结束时间" 
                placeholder="选择时间范围" 
                class="elInpthree" 
                value-format="HH:mm:ss"
                @change="changedatetimertwo" 
                :clearable="false"
                popper-class="elDatePicker">
              </el-time-picker>
              <div v-if="form.startTimeDay && form.endTimeDay" class="date-display">
                {{ form.startTimeDay }} 至 {{ form.endTimeDay }}
              </div>
            </div>
          </div>
          <div class="newBox_list" v-if="form.startDate && form.endDate">
            <div class="newBox_list_title">选择的日期：</div>
            <div class="valueDisplay">{{ formatDate(form.startDate) }} 至 {{ formatDate(form.endDate) }}</div>
          </div>
          <div class="newBox_list" v-if="form.startTimeDay && form.endTimeDay">
            <div class="newBox_list_title">选择的时间：</div>
            <div class="valueDisplay">{{ form.startTimeDay }} 至 {{ form.endTimeDay }}</div>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, defineEmits, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import {
  warnRuleList,
  disRuleList,
  addDisRulet,
  editDisRulet,
  delDisRulet,
} from "@/api/map/earlyWarning.js";

// 定义类型
interface RuleFormData {
  id?: number;
  ais: number;
  aisContent: string | null;
  vhf: number;
  vhfContent: string | null;
  warning: number;
  startDate: string | null;
  endDate: string | null;
  startTimeDay: string | null;
  endTimeDay: string | null;
  envType?: string | null;
  [key: string]: any;
}

interface TableRow {
  id: number;
  ais: number;
  aisContent: string | null;
  vhf: number;
  vhfContent: string | null;
  warning: number;
  startDate?: string | null;
  endDate?: string | null;
  startTimeDay?: string | null;
  endTimeDay?: string | null;
  [key: string]: any;
}

// 定义props
const props = defineProps({
  ruleData: {
    type: Object,
    required: true
  },
  ruleTitle: {
    type: String,
    required: true
  }
});

// 定义emits
const emit = defineEmits([]);

// 日期快捷选项
const dateShortcuts = [
  {
    text: '未来一周',
    value: () => {
      const start = new Date();
      const end = new Date();
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '未来一个月',
    value: () => {
      const start = new Date();
      const end = new Date();
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '未来三个月',
    value: () => {
      const start = new Date();
      const end = new Date();
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 默认时间
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0), 
  new Date(2000, 1, 1, 23, 59, 59)
] as [Date, Date];

// 响应式数据
const tableData = ref<TableRow[]>([]);
const isNew = ref(false);
const form = reactive<RuleFormData>({
  ais: 1,
  aisContent: null,
  vhf: 1,
  vhfContent: null,
  warning: 1,
  startDate: null,
  endDate: null,
  startTimeDay: null,
  endTimeDay: null,
});
const datetimerone = ref<string[]>([]);
const datetimertwo = ref<string[]>([]);

// 引用
const ruleForm = ref();

// 日期格式化函数
function formatDate(date: string | null): string {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}

// 转换布尔值为0/1
function convertBoolToNumber(data: any): any {
  if (typeof data !== 'object' || data === null) return data;
  
  if (Array.isArray(data)) {
    return data.map(item => convertBoolToNumber(item));
  }

  const result: any = {};
  for (const key in data) {
    if (typeof data[key] === 'boolean') {
      result[key] = data[key] ? 1 : 0;
    } else if (typeof data[key] === 'object' && data[key] !== null) {
      result[key] = convertBoolToNumber(data[key]);
    } else {
      result[key] = data[key];
    }
  }
  return result;
}

// 转换后端返回的0/1为对应的布尔值
function processAPIResponse(data: any[]): any[] {
  return data.map(item => {
    const processed = { ...item };
    return processed;
  });
}

// 生命周期
onMounted(() => {
  console.log(props.ruleData);
  getwarnRuleList();
});

// 方法
// 获取全部规则列表
function getwarnRuleList() {
  disRuleList({
    envType: props.ruleData.envKey,
  }).then((res: any) => {
    if (res.code == 200) {
      tableData.value = processAPIResponse(res.rows);
    }
  });
}

// 添加规则
function addRule() {
  // if (tableData.value.length > 0) {
  //   ElMessage.error("当前已有规则，暂时不可添加");
  //   return;
  // } else {
    reseForm();
    updateDateDisplay(); // 确保表单重置后更新显示
    isNew.value = true;
  // }
}

// 修改
function editRule(val: TableRow) {
  reseForm();
  
  // 先复制日期和时间值
  const startDate = val.startDate;
  const endDate = val.endDate;
  const startTimeDay = val.startTimeDay;
  const endTimeDay = val.endTimeDay;
  
  // 然后复制其他值
  Object.assign(form, val);
  
  // 使用nextTick确保DOM更新后再设置日期值
  nextTick(() => {
    // 设置日期选择器的值
    if (startDate && endDate) {
      datetimerone.value = [startDate, endDate];
      console.log('设置日期范围:', datetimerone.value);
    } else {
      datetimerone.value = [];
    }
    
    // 设置时间选择器的值
    if (startTimeDay && endTimeDay) {
      datetimertwo.value = [startTimeDay, endTimeDay];
      console.log('设置时间范围:', datetimertwo.value);
    } else {
      datetimertwo.value = [];
    }
  });
  
  isNew.value = true;
}

// 删除
function delRule(val: TableRow) {
  ElMessageBox.confirm("是否确认删除该规则?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      return delDisRulet(val.id);
    })
    .then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        getwarnRuleList();
      }
    })
    .catch(() => {
      // 取消操作无需处理
    });
}

// 提交新增
function submit() {
  if (form.ais && !form.aisContent) {
    ElMessage.error("请输入报文内容");
    return;
  }
  if (form.vhf && !form.vhfContent) {
    ElMessage.error("请输入VHF喊话内容");
    return;
  }
  
  const submitData = { ...form };
  
  if (form.id) {
    // 修改
    editDisRulet(submitData).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("修改成功");
        isNew.value = false;
        getwarnRuleList();
      }
    });
  } else {
    // 新增
    submitData.envType = props.ruleData.envKey;
    addDisRulet(submitData).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("操作成功");
        isNew.value = false;
        getwarnRuleList();
      }
    });
  }
}

function reseForm() {
  Object.assign(form, {
    ais: 1,
    aisContent: null,
    vhf: 1,
    vhfContent: null,
    warning: 1,
    startDate: null,
    endDate: null,
    startTimeDay: null,
    endTimeDay: null,
  });
  datetimerone.value = [];
  datetimertwo.value = [];
}

// 关闭新建规则弹窗
function handleClose() {
  isNew.value = false;
}

function tableRowClassName({ row, rowIndex }: { row: TableRow, rowIndex: number }) {
  if (rowIndex % 2 == 0) {
    return "warning-row";
  }
  return "";
}

function changedatetimerone(e: string[]) {
  console.log('日期变更:', e);
  if (e && e.length === 2) {
    form.startDate = e[0];
    form.endDate = e[1];
  } else {
    form.startDate = null;
    form.endDate = null;
  }
}

function changedatetimertwo(e: string[]) {
  console.log('时间变更:', e);
  if (e && e.length === 2) {
    form.startTimeDay = e[0];
    form.endTimeDay = e[1];
  } else {
    form.startTimeDay = null;
    form.endTimeDay = null;
  }
}

// 特意添加一个函数，用于重置表单后手动触发数据绑定更新
function updateDateDisplay() {
  nextTick(() => {
    if (form.startDate && form.endDate) {
      datetimerone.value = [form.startDate, form.endDate];
    } else {
      datetimerone.value = [];
    }
    
    if (form.startTimeDay && form.endTimeDay) {
      datetimertwo.value = [form.startTimeDay, form.endTimeDay];
    } else {
      datetimertwo.value = [];
    }
  });
}
</script>

<style>
.box {
  width: 100%;
}

.newBox {
  color: #333333;
}

.newBox_list {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.newBox_list_title {
  min-width: 100px;
  text-align: right;
  padding-right: 10px;
}

.elInp {
  width: 200px;
  margin-left: 10px;
}

.elInpMn {
  width: 80px;
}

.elInpTwo {
  width: 290px;
}

.elInpthree {
  width: 290px;
}

.btn {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.custom-date-wrapper {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.date-display {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}

.valueDisplay {
  color: #409EFF;
  padding: 5px 10px;
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 4px;
}

/* 自定义日期选择器样式 */
.elDatePicker {
  background-color: #ffffff !important;
  border: 1px solid #e4e7ed !important;
  color: #333333 !important;

  .el-date-picker__header {
    color: #333333;
  }

  .el-date-table th {
    color: #606266;
  }

  .el-date-table td {
    color: #606266;
  }

  .el-date-table td.available:hover {
    color: #409EFF;
  }

  .el-date-table td.today {
    color: #409EFF;
  }

  .el-date-table td.current:not(.disabled) {
    color: #fff;
    background-color: #409EFF;
  }

  .el-date-picker__header-label {
    color: #333333;
  }

  .el-picker-panel__shortcut {
    color: #606266;
  }

  .el-picker-panel__shortcut:hover {
    color: #409EFF;
  }

  .el-time-spinner__item {
    color: #606266;
  }

  .el-time-spinner__item.active {
    color: #409EFF;
  }

  .el-time-spinner__item:hover {
    color: #409EFF;
    background: #f5f7fa;
  }

  .el-time-panel__btn.cancel {
    color: #606266;
  }

  .el-time-panel__btn.confirm {
    color: #ffffff;
    background: #409EFF;
    border: 1px solid #409EFF;
  }

  .available.in-range {
    color: #409EFF;
  }

  .el-year-table td .cell {
    color: #606266;
  }

  .el-year-table td.current:not(.disabled) .cell {
    color: #409EFF;
  }
}

.elDateSeletc.el-select-dropdown {
  color: #333333; 
  background: #ffffff; 

  .el-select-dropdown__item {
    color: #333333;
    background: #ffffff;
  }

  .el-select-dropdown__item:hover {
    color: #409EFF;
    background: rgba(64, 158, 255, 0.1);
  }

  .selected {
    color: #409EFF;
    background: rgba(64, 158, 255, 0.1);
  }
}
</style>
<style scoped src="@/assets/datePark.css"></style>